﻿using System;
using jade.core;
using jade.core.behaviours;
using jade.lang.acl;
using jade.domain.FIPAAgentManagement;
using jade.content.lang;
using log4net;
using jade.content;
using jade.content.lang.leap;
using Action = jade.content.onto.basic.Action;
using jade.domain.JADEAgentManagement;
using jade.content.onto.basic;
using GatewayUtil.agents.ontology;
using System.IO;
using java.io;



namespace Agents
{
    public class WeatherAgent : Agent
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(WeatherAgent));

        public static Codec codec = new LEAPCodec();
        public override void setup()
        {
            log.Info("Starting agent with name " + this.getAID().getLocalName());

            getContentManager().registerLanguage(codec);
            getContentManager().registerOntology(FIPAManagementOntology.getInstance());
            getContentManager().registerOntology(JADEManagementOntology.getInstance());

            this.getContentManager().setValidationMode(false);
            this.setEnabledO2ACommunication(true, 30);

            string logPath = (string)getArguments()[0];

            addBehaviour(new WeatherBehaviour(this, 2*60*1000,logPath));
            debug("Gateway agent is set up!");
        }

        public override void takeDown()
        {
            base.takeDown();
            log.Info("Agent " + this.getAID().getLocalName() + " taken down!");
        }

        private void debug(string p)
        {
            log.Debug(this.getLocalName() + ": " + p);
        }
        private void error(string p)
        {
            log.Error(this.getLocalName() + ": " + p);
        }

        private void error(Exception e)
        {
            log.Error(e);
        }


        class WeatherBehaviour : TickerBehaviour
        {
            
            string logPath;
            public WeatherBehaviour(Agent a, long tickTime, string logPath)
                : base(a,tickTime)
            {
                ((WeatherAgent)this.myAgent).debug("WeatherBehaviour started!");
                this.logPath = logPath;
            }

            public void actionTick()
            {
                TextWriter writer=null;
                try
                {
                    WSRequest wsRequest = new WSRequest();
                    wsRequest.setServiceURL("http://www.deeptraining.com/webservices/weather.asmx?WSDL");
                    wsRequest.setServiceName("Weather");
                    wsRequest.setMethodName("GetWeather");
                    jade.util.leap.List args = new jade.util.leap.ArrayList();
                    args.add("Boston");
                    wsRequest.addArguments(args);

                    writer = System.IO.File.AppendText(logPath + "/ws_log.txt");
                    writer.WriteLine(DateTime.Now + ": WeatherAgent Request = " + wsRequest.getServiceURL() + ", " + wsRequest.getServiceName() + ", " + wsRequest.getMethodName() + ", " + args.get(0));


                    

                    ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
                    msg.addReceiver(new AID("wsInvokerAgent", false));
                    msg.setLanguage(WeatherAgent.codec.getName());
                    msg.setOntology(DynamicWSOntology.getInstance().getName());
                    this.myAgent.getContentManager().registerOntology(DynamicWSOntology.getInstance());

                    Action action = new Action(new AID("wsInvokerAgent", false), (AgentAction)wsRequest);
                    this.myAgent.getContentManager().fillContent(msg, action);

                    ((WeatherAgent)this.myAgent).debug("Sending request");
                    this.myAgent.send(msg);
                    ((WeatherAgent)this.myAgent).debug("The message was successfully sent");

                    msg = base.myAgent.blockingReceive();
                    log.Debug("Received response");

                    // extract a result object
                    ContentElement contentE = (ContentElement)myAgent.getContentManager().extractContent(msg);
                    Result res = (Result)contentE;
                    Object val = res.getValue();

                    if (val is Concept)
                    {

                        WSResponse wsResponse = (WSResponse)val;
                        Object o = wsResponse.getResponseObject();

                        writer.WriteLine(DateTime.Now + ": WeatherAgent Response = " + o);

                        log.Debug(o);
                    }
                    else
                    {
                        log.Error("Object is not a AgentAction! is a " + ((Concept)val).GetType().FullName);
                    }



                }
                catch (Exception e)
                {
                    log.Error("Exception in WSInvokerAgent", e);
                    throw e;
                }
                finally
                {
                    writer.Close();
                }
                
                
            }



            public override void onTick()
            {
                this.actionTick();
            }
        }




    }
}



